import { CHint } from "./CHint";
import { CountDown } from "./CountDown";
import { DataMgr } from "./DataMgr";
import { EventMgr } from "./EventMgr";
import { Fail } from "./Fail";
import { Lose } from "./Lose";
import { Monster } from "./Monster";
import { MsgCode } from "./MsgCode";
import { Player } from "./Player";
import { RoomBox } from "./RoomBox";
import { SocketMgr } from "./SocketMgr";
import { Success } from "./Success";
import uni from "./third_part/uni";
import { Utils } from "./Utils";

const { regClass, property } = Laya;

@regClass()
export class Game extends Laya.Script {
    @property(Laya.GBox)
    public mapBox: Laya.GBox;

    @property(Laya.GBox)
    public roomBox: Laya.GBox;

    @property(Laya.GBox)
    public playerBox: Laya.GBox;

    @property(Laya.Prefab)
    public monsterFab: Laya.Prefab;

    @property(Laya.Prefab)
    public playerFab: Laya.Prefab;

    @property(Laya.GTextField)
    public labMyAsset: Laya.GTextField;

    @property(Laya.GTextField)
    public labLastRoom: Laya.GTextField;

    @property(Laya.GTextField)
    public labPeriod: Laya.GTextField;

    @property(Laya.GTextField)
    public labGameNum: Laya.GTextField;

    @property(Laya.GComboBox)
    public comBox: Laya.GComboBox;

    @property(Laya.GBox)
    public comming: Laya.GBox;

    @property(Laya.GButton)
    public btnSpin: Laya.GButton;

    @property(Laya.GButton)
    public btnMute: Laya.GButton;

    @property(Laya.Animator2D)
    public commingAni: Laya.Animator2D;

    @property(Laya.GBox)
    public winNoBet: Laya.GBox;

    @property(Laya.GBox)
    public winFail: Laya.GBox;

    @property(Laya.GBox)
    public winSuccess: Laya.GBox;

    @property(CountDown)
    public coundDown: CountDown;

    @property(RoomBox)
    public roomScript: RoomBox;

    @property(Laya.GTextField)
    public txtLaba: Laya.GTextField;

    @property(Laya.GPanel)
    public labaPanel: Laya.GPanel;

    public tiledMap: Laya.TiledMap = new Laya.TiledMap();

    private playerArea: number[][] = [];

    private graph: any;
    private opts: any;

    private roomAreas: number[][][] = [];

    private roomsDoor: number[][][] = [];

    private curRoomIndex: number = 0;

    private lastSpinTime = 0;

    private borth_gridX = 0;
    private borth_gridY = 0;

    onStart() {
        console.log("Game start");
        uni.postMessage({ data: { cmd: "loadEnd" } });
        this.owner.on(Laya.Event.RESIZE, this, this.onResize);

        this.comming.visible = false;
        this.roomBox.visible = false;
        for (let i = 0; i < 8; i++) {
            let room = this.roomBox.getChildAt(i);
            room.on(Laya.Event.CLICK, this, this.onRoomClick, [i]);
        }
        this.btnSpin.on(Laya.Event.CLICK, this, this.onSpinClick);
        this.btnMute.on(Laya.Event.CHANGED, this, this.onMuteChange);


        this.addListen();
        this.createMap();
        Laya.SoundManager.playMusic("resources/sound/bg.mp3", 0);

        this.startLaba();
    }

    addListen() {
        SocketMgr.getInstance().addEventListener(MsgCode.WS_GAME_BATTLE_MORE, this.onGameBattleMore, this);
        SocketMgr.getInstance().addEventListener(MsgCode.WS_GAME_BATTLE_NORMAL, this.onGameBattleNomal, this);
        SocketMgr.getInstance().addEventListener(MsgCode.WS_GAME_BATTLE_BET, this.onGameBattleBet, this);
        SocketMgr.getInstance().addEventListener(MsgCode.WS_GAME_BATTLE_START, this.onGameBattleStart, this);
        SocketMgr.getInstance().addEventListener(MsgCode.WS_GAME_BATTLE_SETTLEMENT, this.onGameBattleSettle, this);
        SocketMgr.getInstance().addEventListener(MsgCode.WS_GAME_BATTLE_END, this.onGameBattleEnd, this);
    }

    createMap() {
        this.tiledMap.createMap("resources/map/map2.tmj",
            new Laya.Rectangle(0, 0, this.mapBox.width, this.mapBox.height),
            Laya.Handler.create(this, this.onLoadMapEnd)
        );
    }

    private onLoadMapEnd() {
        let map = this.tiledMap.mapSprite().removeSelf();
        this.mapBox.addChild(map);
        this.roomBox.visible = true;
        this.initBlockDatas();
        this.initRoomArea();
        SocketMgr.getInstance().send(
            { "type": "game_battle", "status": "1" }
            , this.onBattleStart, this);
    }

    private onResize() {

    }

    private initBlockDatas() {
        let blockArr = [];
        this.playerArea.length = 0;
        let layer_player = this.tiledMap.getLayerByName("player");
        let layer_block = this.tiledMap.getLayerByName("block");
        for (let i = 0; i < this.tiledMap.numColumnsTile; i++) {
            let arr = [];
            for (let j = 0; j < this.tiledMap.numRowsTile; j++) {
                let tile_player = layer_player.getTileData(i, j);
                let tile_block = layer_block.getTileData(i, j);
                if (tile_player) {
                    this.playerArea.push([i, j]);
                }

                if (tile_block) {
                    arr.push(1);
                } else {
                    arr.push(0);
                }
            }
            blockArr.push(arr);
        }

        this.graph = new (window as any).Graph(blockArr);
        this.opts = [];
        this.opts.closest = true;
        this.opts.heuristic = (window as any).astar.heuristics.diagonal;

    }

    private initRoomArea() {
        for (let k = 0; k < 8; k++) {
            this.roomAreas[k] = [];
            let layer_room = this.tiledMap.getLayerByName(`room${k}`);
            for (let i = 0; i < this.tiledMap.numColumnsTile; i++) {
                for (let j = 0; j < this.tiledMap.numRowsTile; j++) {
                    let tile_room = layer_room.getTileData(i, j);
                    if (tile_room) {
                        this.roomAreas[k].push([i, j]);
                    }
                }
            }
        }

        for (let k = 0; k < 8; k++) {
            this.roomsDoor[k] = [];
            let door_room = this.tiledMap.getLayerByName(`door${k}`);
            for (let i = 0; i < this.tiledMap.numColumnsTile; i++) {
                for (let j = 0; j < this.tiledMap.numRowsTile; j++) {
                    let tile_room = door_room.getTileData(i, j);
                    if (tile_room) {
                        this.roomsDoor[k].push([i, j]);
                    }
                }
            }
        }

        let layer_monster = this.tiledMap.getLayerByName("monster");
        for (let i = 0; i < this.tiledMap.numColumnsTile; i++) {
            for (let j = 0; j < this.tiledMap.numRowsTile; j++) {
                let tile_monster = layer_monster.getTileData(i, j);
                if (tile_monster) {
                    this.borth_gridX = i;
                    this.borth_gridY = j;
                    break;
                }
            }
        }
    }

    onDestroy(): void {
        EventMgr.instance.offAllCaller(this);
    }

    createMonster() {
        let monster: Laya.Sprite = Laya.Pool.getItemByCreateFun("monster_pool", () => {
            let m = this.monsterFab.create() as Laya.Sprite;
            return m;
        }, this);

        let monsterScript = monster.getComponent(Monster);
        monsterScript.setStarGrid(this.borth_gridX, this.borth_gridY, this.tiledMap.tileWidth, this.tiledMap.tileHeight);
        this.playerBox.addChild(monster);
    }

    createIdlePlayer(playerinfo: any, isSelf?: boolean) {
        if (this.playerArea.length == 0)
            return;
        let player: Laya.Sprite = Laya.Pool.getItemByCreateFun("player_pool", () => {
            let p = this.playerFab.create() as Laya.Sprite;
            return p;
        }, this);

        let rd = Utils.randomRange(0, this.playerArea.length - 1);
        let arr = this.playerArea[rd];
        let playerScript: Player = player.getComponent(Player);
        playerScript.setPlayInfo(playerinfo, isSelf);
        playerScript.setStarGrid(arr[0], arr[1], this.tiledMap.tileWidth, this.tiledMap.tileHeight);
        playerScript.playIdle();
        this.playerBox.addChild(player);
    }

    createRoomPlayer(playerinfo: any, roomIndex: number, isSelf?: boolean) {
        if (this.roomAreas.length == 0)
            return;
        let player: Laya.Sprite = Laya.Pool.getItemByCreateFun("player_pool", () => {
            let p = this.playerFab.create() as Laya.Sprite;
            return p;
        }, this);
        let roomArea = this.roomAreas[roomIndex];
        let rd = Utils.randomRange(0, roomArea.length - 1);
        let arr = roomArea[rd];
        let playerScript: Player = player.getComponent(Player);
        playerScript.setPlayInfo(playerinfo, isSelf);
        playerScript.setStarGrid(arr[0], arr[1], this.tiledMap.tileWidth, this.tiledMap.tileHeight);
        playerScript.playIdle();
        this.playerBox.addChild(player);
    }

    onBattleStart(_data: any) {

    }

    onBattleMore() {
        for (let i = this.playerBox.numChildren - 1; i >= 0; i--) {
            let cld = this.playerBox.getChildAt(i);
            if (cld.getComponent(Monster) != void 0) {
                let n = cld.removeSelf();
                Laya.Pool.recover("monster_pool", n);
            } else if (cld.getComponent(Player) != void 0) {
                let n = cld.removeSelf();
                Laya.Pool.recover("player_pool", n);
            }
        }


        let data = DataMgr.getInstance().gameData;
        if (data) {
            if (data.waitUsers) {
                for (let i = 0; i < data.waitUsers.length; i++) {
                    this.createIdlePlayer(data.waitUsers[i], data.waitUsers[i].userId == data.betUser.userId);
                }
            }

            if (data.rooms) {
                this.initRoomPlayers();
            }

            this.comBox.items = data.minBet.split(",");
            if (this.comBox.text == void 0 || this.comBox.text.length <= 0)
                this.comBox.selectedIndex = 0;
            this.labLastRoom.text = `上期星盗去了${Utils.keepOnlyChinese(data.lastRoomName)}`;
            this.labPeriod.text = `${data.period}期-人满即开`;
            this.labGameNum.text = `${data.joinNum}/${data.minNum}`;
            let amount: number = data.betUser.amount
            this.labMyAsset.text = amount.toFixed(2);

            if (data.status == "PLAYING") {
                this.coundDown.owner.visible = true;
                let d = new Date(data.stopBetTime);
                let t = d.getTime() - DataMgr.getInstance().serverTime;
                console.log("t == " + t);
                this.roomScript.openAllDoors(0);
                this.coundDown.startDown(t, Laya.Handler.create(this, () => {
                    this.comming.visible = true;
                    this.commingAni.play("comming", 0);
                    Laya.SoundManager.playSound("resources/sound/effect.mp3");
                    this.roomScript.closeAllDoors(0);
                }));
            } else {
                this.coundDown.owner.visible = false;
                this.roomScript.closeAllDoors(0);
            }
        }

        if (data.rooms) {
            for (let i = 0; i < data.rooms.length; i++) {
                let room = data.rooms[i];
                let box = this.roomBox.getChildByName<Laya.GBox>(`room${i}`);
                if (box) {
                    let lab_name = box.getChildByName("img").getChildByName<Laya.GTextField>("room_name");
                    lab_name.text = Utils.keepOnlyChinese(room.roomName);

                    let labAmount = box.getChildByName("box").getChildByName<Laya.GTextField>("txt");
                    labAmount.text = room.betAmount;
                }
            }
        }
        this.updateRoomSelect();
    }

    private initRoomPlayers() {
        let data = DataMgr.getInstance().gameData;
        if (data == void 0)
            return;
        for (let i = 0; i < data.rooms.length; i++) {
            let room = data.rooms[i];
            let roomIndex = data.rooms.findIndex((ele: any) => ele.roomId == room.roomId);
            if (room && room.joinUsers) {
                for (let j = 0; j < room.joinUsers.length; j++) {
                    this.createRoomPlayer(room.joinUsers[j], roomIndex, room.joinUsers[j].userId == data.betUser.userId);
                }
            }
        }
    }

    private onRoomClick(index: number, evt: Laya.Event) {
        if (this.lastSpinTime > 0 && Laya.Browser.now() - this.lastSpinTime < 300) {
            return;
        }
        this.curRoomIndex = index;
        this.updateRoomSelect();
        let data = DataMgr.getInstance().gameData;
        if (data) {
            let roomId = data.rooms[this.curRoomIndex].roomId;
            let amountNum = 0;
            SocketMgr.getInstance().send(
                { type: "game_battle", status: 3, roomId: roomId, amount: amountNum, period: data.period }
                , this.onSpinReseult, this);
            this.lastSpinTime = Laya.Browser.now();
        }
    }

    private onSpinClick(evt: Laya.Event): void {
        evt.stopPropagation();
        if (evt.target.name == "btnSpin") {
            if (this.lastSpinTime > 0 && Laya.Browser.now() - this.lastSpinTime < 300) {
                return;
            }
            let data = DataMgr.getInstance().gameData;
            if (data) {
                if (data.status != "PLAYING") {
                    CHint.getInstance().showText(" 游戏未开始");
                    return;
                }
            }
            let roomId = data.rooms[this.curRoomIndex].roomId;
            let amountNum = Number(this.comBox.text);
            SocketMgr.getInstance().send(
                { type: "game_battle", status: 3, roomId: roomId, amount: amountNum, period: data.period }
                , this.onSpinReseult, this);
            this.lastSpinTime = Laya.Browser.now();
        }
    }

    updateRoomSelect() {
        for (let i = 0; i < 8; i++) {
            let gbox = this.roomBox.getChildByName<Laya.GBox>(`room${i}`);
            gbox.getChildByName("xz").visible = this.curRoomIndex == i;
        }
    }

    onSpinReseult(_data: any) {
        CHint.getInstance().showText("下注成功");
    }

    private onGameBattleMore(data: any) {
        if (data.ok) {
            DataMgr.getInstance().gameData = data.data;
            DataMgr.getInstance().serverTimeDelay = data.now - Laya.Browser.now();
            this.onBattleMore();
        }
    }

    private onGameBattleNomal(data: any) {
        if (data.ok) {
            if (data.data.newRoomId && data.data.newAmount) {
                let notHave = false;
                if (!this.isHavaPlayer(data.data.userId)) {
                    let roomIndex = data.data.rooms.findIndex((ele: any) => ele.roomId == data.data.newRoomId);
                    this.createRoomPlayer(data.data, roomIndex);
                    notHave = true;
                }
                if (data.data.oldRoomId == void 0 || data.data.oldAmount == void 0) {
                    if (notHave)
                        this.playerGotoRoom(data.data.userId, data.data.newRoomId, false);
                    else
                        this.playerGotoRoom(data.data.userId, data.data.newRoomId, true);
                } else if (data.data.oldRoomId != data.data.newRoomId) {
                    this.playerGotoRoom(data.data.userId, data.data.newRoomId);
                }
            } else {
                if (!this.isHavaPlayer(data.data.userId)) {
                    this.createIdlePlayer(data.data);
                }
            }

            if (data.data.rooms) {
                for (let i = 0; i < data.data.rooms.length; i++) {
                    let room = data.data.rooms[i];
                    let box = this.roomBox.getChildByName<Laya.GBox>(`room${i}`);
                    if (box) {
                        let labAmount = box.getChildByName("box").getChildByName<Laya.GTextField>("txt");
                        if (labAmount.text != room.betAmount) {
                            labAmount.scale(1, 1);
                            Laya.Tween.create(labAmount).duration(100).to("scaleX", 1.2).to("scaleY", 1.2).then(() => {
                                Laya.Tween.create(labAmount).duration(100).to("scaleX", 1).to("scaleY", 1)
                            });
                        }
                        labAmount.text = room.betAmount;
                    }
                }
            }
        }
    }

    private onGameBattleBet(data: any) {
        console.log("onGameBattleBet");
        if (data.ok) {
            let ani = true;
            let old_data = DataMgr.getInstance().gameData;
            if (old_data && old_data.betUser && old_data.betUser.roomId != void 0) {
                ani = false;
            }
            DataMgr.getInstance().gameData = data.data;
            if (data.data.betUser) {
                let rooid = data.data.betUser.roomId;
                let userid = data.data.betUser.userId;
                let amount: number = data.data.betUser.amount
                this.labMyAsset.text = amount.toFixed(2);
                if (old_data.betUser.roomId != rooid)
                    this.playerGotoRoom(userid, rooid, ani);
            }

            if (data.data.rooms) {
                for (let i = 0; i < data.data.rooms.length; i++) {
                    let room = data.data.rooms[i];
                    let box = this.roomBox.getChildByName<Laya.GBox>(`room${i}`);
                    if (box) {
                        let labAmount = box.getChildByName("box").getChildByName<Laya.GTextField>("txt");
                        labAmount.text = room.betAmount;
                    }
                }
            }
        }
    }

    private onGameBattleStart(data: any) {
        console.log("onGameBattleStart");
        if (data.ok) {
            DataMgr.getInstance().gameData = data.data;
            DataMgr.getInstance().serverTimeDelay = data.now - Laya.Browser.now();
            this.coundDown.owner.visible = true;
            let d = new Date(data.data.stopBetTime);
            let t = d.getTime() - DataMgr.getInstance().serverTime;
            console.log("t == " + t);
            this.roomScript.openAllDoors(300);
            this.coundDown.startDown(t, Laya.Handler.create(this, () => {
                this.comming.visible = true;
                this.commingAni.play("comming", 0);
                Laya.SoundManager.playSound("resources/sound/effect.mp3");
                this.roomScript.closeAllDoors(300);
            }));
        }
    }

    private onGameBattleSettle(data: any) {
        console.log("onGameBattleSettle");
        if (data.ok) {
            this.commingAni.stop();
            this.comming.visible = false;

            DataMgr.getInstance().gameData = data.data;
            let roomId = data.data.killRoomId;


            let fail = this.winNoBet as Fail;
            fail.labKill.text = `星盗杀掉 [color=#869EED][ ${Utils.keepOnlyChinese(data.data.killRoomName)} ][/color] 里的所有人`;
            fail.labCount.text = data.data.killRoomAmount || 0;

            let success = this.winSuccess as Success;
            success.labCount1.text = data.data.betUser.betAmount || 0;
            success.labCount2.text = data.data.betUser.winAmount || 0;
            success.labCount3.text = data.data.betUser.winExtra || 0;

            let lose = this.winFail as Lose;
            lose.labCount1.text = data.data.betUser.betAmount || 0;
            lose.labCount2.text = data.data.betUser.winAmount || 0;
            lose.labCount3.text = data.data.betUser.loseExtra || 0;

            this.createMonster();
            this.monsterGotoDoor(roomId);
        }
    }

    private onGameBattleEnd(data: any) {
        console.log("onGameBattleEnd");
        if (data.ok) {
            this.winNoBet.visible = false;
            this.winSuccess.visible = false;
            this.winFail.visible = false;
            DataMgr.getInstance().gameData = data.data;
            let amount: number = data.data.betUser.amount;
            this.labMyAsset.text = amount.toFixed(2);
            Laya.timer.once(1000, this, () => {
                SocketMgr.getInstance().send(
                    { "type": "game_battle", "status": "1" }
                    , this.onBattleStart, this);
            })
        }
    }

    private playerGotoRoom(userId: number, roomId: number, withAni?: boolean) {
        let data = DataMgr.getInstance().gameData;
        if (!data || !data.rooms) return;

        // find the index of the room with matching roomId
        let roomIndex = data.rooms.findIndex((ele: any) => ele.roomId == roomId);
        if (roomIndex < 0) {
            console.warn("playerGotoRoom: roomId not found", roomId);
            return;
        }

        let areas: number[][] = this.roomAreas[roomIndex];
        if (!areas || areas.length === 0) {
            console.warn("playerGotoRoom: no areas for roomIndex", roomIndex);
            return;
        }

        let rd = Utils.randomRange(0, areas.length - 1);
        let area = areas[rd];
        for (let i = 0; i < this.playerBox.numChildren; i++) {
            let child = this.playerBox.getChildAt(i);
            let playerScript = child.getComponent(Player);
            if (playerScript && playerScript.userInfo.userId == userId) {
                let start = this.graph.grid[playerScript.StartGridX][playerScript.StartGridY];
                let end = this.graph.grid[area[0]][area[1]];
                let paths = (window as any).astar.search(this.graph, start, end, {
                    closest: this.opts.closest
                }) || [];
                if (paths.length === 0 || !withAni) {
                    // nothing to move, just ensure idle state
                    playerScript.setStarGrid(area[0], area[1], this.tiledMap.tileWidth, this.tiledMap.tileHeight);
                    playerScript.playIdle(true);
                } else {
                    playerScript.playRun(paths);
                }
                break;
            }
        }
    }


    private monsterGotoDoor(roomId: number) {
        let data = DataMgr.getInstance().gameData;
        if (!data || !data.rooms) return;

        // find the index of the room with matching roomId
        let roomIndex = data.rooms.findIndex((ele: any) => ele.roomId == roomId);
        if (roomIndex < 0) {
            console.warn("monsterGotoDoor: roomId not found", roomId);
            return;
        }

        let doors: number[][] = this.roomsDoor[roomIndex];
        if (!doors || doors.length === 0) {
            console.warn("monsterGotoDoor: no areas for roomIndex", roomIndex);
            return;
        }
        let door = doors[0];
        for (let i = 0; i < this.playerBox.numChildren; i++) {
            let child = this.playerBox.getChildAt(i);
            let monsterScript = child.getComponent(Monster);
            if (monsterScript) {
                let start = this.graph.grid[monsterScript.StartGridX][monsterScript.StartGridY];
                let gridX = door[0];
                let gridY = door[1];
                let end = this.graph.grid[gridX][gridY];
                let paths = (window as any).astar.search(this.graph, start, end, {
                    closest: this.opts.closest
                }) || [];
                monsterScript.playRun(paths, Laya.Handler.create(this, this.openDoor, [roomIndex, gridX, gridY]));
                break;
            }
        }
    }

    private openDoor(roomIndex: number, gridX: number, gridY: number) {
        this.roomScript.openDoor(roomIndex, 300, Laya.Handler.create(this, this.monsterGotoRoom, [roomIndex, gridX, gridY]));
    }

    private monsterGotoRoom(roomIndex: number, gridX: number, gridY: number) {
        let data = DataMgr.getInstance().gameData;
        if (!data || !data.rooms) return;
        let areas: number[][] = this.roomAreas[roomIndex];
        if (!areas || areas.length === 0) {
            console.warn("monsterGotoRoom: no areas for roomIndex", roomIndex);
            return;
        }

        let rd = Utils.randomRange(0, areas.length - 1);
        let area = areas[rd];
        for (let i = 0; i < this.playerBox.numChildren; i++) {
            let child = this.playerBox.getChildAt(i);
            let monsterScript = child.getComponent(Monster);
            if (monsterScript) {
                let start = this.graph.grid[gridX][gridY];
                let end = this.graph.grid[area[0]][area[1]];
                let paths = (window as any).astar.search(this.graph, start, end, {
                    closest: this.opts.closest
                }) || [];
                monsterScript.playRun(paths, Laya.Handler.create(this, this.onPopSettleUI, [area[0], area[1]]));
                break;
            }
        }
    }

    private onPopSettleUI(startX: number, startY: number) {
        let data = DataMgr.getInstance().gameData;
        if (data == void 0)
            return;
        Laya.SoundManager.playSound("resources/sound/settlement.mp3");
        if (data.betUser == void 0 || data.betUser.roomId == void 0) {
            //no bet
            this.winFail.visible = false;
            this.winSuccess.visible = false;
            this.winNoBet.visible = true;
        } else {
            this.winNoBet.visible = false;
            if (data.betUser && data.betUser.roomId == data.killRoomId) {
                //fail
                this.winFail.visible = true;
                this.winSuccess.visible = false;
            } else {
                //success
                this.winFail.visible = false;
                this.winSuccess.visible = true;
            }
        }

        //walk to birth pos
        for (let i = 0; i < this.playerBox.numChildren; i++) {
            let child = this.playerBox.getChildAt(i);
            let monsterScript = child.getComponent(Monster);
            if (monsterScript) {
                let start = this.graph.grid[startX][startY];
                let end = this.graph.grid[this.borth_gridX][this.borth_gridY];
                let paths = (window as any).astar.search(this.graph, start, end, {
                    closest: this.opts.closest
                }) || [];
                monsterScript.playRun(paths, null, false);
                break;
            }
        }
    }

    onMouseClick(evt: Laya.Event): void {
        if (evt.target.name == "btn_back") {
            uni.postMessage({ data: { cmd: "back" } });
        }
        else if (evt.target.name == "btn_play") {
            uni.postMessage({ data: { cmd: "BattleRoyaleRule" } });
        } else if (evt.target.name == "btn_rank_total") {
            uni.postMessage({ data: { cmd: "BattleRoyaleRanking" } });
        } else if (evt.target.name == "btn_recover") {
            uni.postMessage({ data: { cmd: "BattleRoyaleGameRecord" } });
        } else if (evt.target.name == "btn_rank_act") {
            uni.postMessage({ data: { cmd: "BattleRoyaleActivityRanking" } });
        }
    }

    isHavaPlayer(userId: number) {
        for (let i = 0; i < this.playerBox.numChildren; i++) {
            let child = this.playerBox.getChildAt(i);
            let playerScript = child.getComponent(Player);
            if (playerScript && playerScript.userInfo.userId == userId) {
                return true;
            }
        }
        return false;
    }

    private startLaba() {
        this.txtLaba.x = this.labaPanel.width;
        this.txtLaba.autoSize = true;
        Laya.Tween.create(this.txtLaba).duration(20000).to("x", -this.txtLaba.width).then(() => {

        }).repeat(-1);
    }

    private onMuteChange() {
        Laya.SoundManager.muted = this.btnMute.selected;
    }
}